<template>
  <div class="app-container">
    <div class="customContainer towTabel">
      <el-form :inline="true">
        <el-form-item>
          <span style="margin-right:10px">供货渠道：{{this.saveForm.type==1?"供应商":"中央仓"}}</span>
          <dj-store-select :category="448" :needItem="true" :showDelete="false" :defaultStore="formInline.store_id" @change="selectStoreChanged" />
          <span style="color: #888;">使用区域：</span>
          <el-select v-model="searchObj.area_type" size="small">
            <el-option v-for="item in area_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <dj-gift-search-select @change="searchTextChanged" @keyupEnter="searchClick" />
          <div class="el-button--small el-button el-button el-button--primary" @click="searchClick"> <span>筛选</span></div>
          <div class="el-button--small el-button el-button el-button--primary" @click="getCar"> <span>刷新</span></div>
        </el-form-item>
      </el-form>
      <el-table highlight-current-row :data="carList" v-loading.body="listLoading" border size="small" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="36"></el-table-column>
        <el-table-column align="center" label="序号" width="70" type="index"></el-table-column>
        <el-table-column align="center" label="图片" prop="gift_id" width="80">
          <template slot-scope="scope">
            <div style="position:relative">
              <div class="images" :class="[scope.row.ratio<1?'h':'w']"><img :src="scope.row.thumb" /></div>
              <div v-show="scope.row.is_on_sale==0" style="position:absolute;top:0px;left:0px">
                <img src="../../assets/images/yixiajia.png" width="60px">
              </div>
              <div style="position:absolute;top:0px;left:0px；z-index:10" v-viewer class="images"
                :class="[scope.row.ratio<1?'h':'w',scope.row.is_on_sale==0?'off_sale':'']">
                <img :src="scope.row.thumb" :data-source="scope.row.img" class="image" :key="scope.row.thumb" :alt="scope.row.img.split('?image=').pop()">
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称" prop="gift_id" @click="gift_other_information = true">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column align="center" label="礼品编号" prop="gift_id"></el-table-column>
        <el-table-column align="center" label="神采编号" prop="no_obsolete"></el-table-column>
        <el-table-column align="center" label="国标码" prop="gb_code"></el-table-column>
        <el-table-column align="center" label="进货价（元）" prop="money_sell">
          <template slot-scope="scope"><span>{{scope.row.money_sell|keepTwoNum}}</span></template>
        </el-table-column>
        <el-table-column v-if="saveForm.type==2" align="center" label="剩余库存（个）" prop="house_num"></el-table-column>
        <el-table-column align="center" label="箱规（个/箱）" prop="box_num">
        </el-table-column>
        <el-table-column align="center" label="数量（个）">
          <template slot-scope="scope">
            <el-input onkeypress="return event.which>=48&&event.which<=57" type="number" onmousewheel="return false;" v-model="scope.row.num" placeholder="数量"
              :disabled="!scope.row.isEdit" @change="numberChange(scope.$index)" style="text-align:center"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="金额小计（元）">
          <template slot-scope="scope">
            <span>{{scope.row.num*scope.row.money_sell|keepTwoNum}} </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="使用区域">
          <template slot-scope="scope">
            <el-button type="text" @click="regionUse(scope.row)" :disabled="!scope.row.isEdit">
              {{scope.row.area_type==100||scope.row.area_type==1?'礼品机区域':scope.row.area_type==200||scope.row.area_type==2?'礼品柜区域':scope.row.area_type==300||scope.row.area_type==3?'摊位机区域':scope.row.area_type==400||scope.row.area_type==4?'企划区域':scope.row.area_type==500||scope.row.area_type==5?'其他区域':'未配置'}}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" width="240">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" :maxlength="24" :disabled="!scope.row.isEdit"></el-input>
          </template>
        </el-table-column>
        <!-- 列表的操作按钮 -->
        <el-table-column align="center" label="操作" width="160">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.isEdit" plain @click="onEditSaveCancel(1,scope)" type="primary" size="mini" style="margin:auto">编辑</el-button>
            <el-button v-if="scope.row.isEdit" plain @click="onEditSaveCancel(2,scope)" type="primary" size="mini" style="margin:auto">保存</el-button>
            <el-button v-if="scope.row.isEdit" plain @click="onEditSaveCancel(3,scope)" type="info" size="mini" style="margin:auto">取消</el-button>
            <el-button v-if="!scope.row.isEdit" plain @click="delClick(scope)" type="danger" size="mini">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表2 -->
      <el-table :data="top_list" highlight-current-row v-loading.body="listLoading" border size="small" style="margin-top:10px">
        <el-table-column label="门店订货指标" width="150" align="center" prop="name"></el-table-column>
        <el-table-column label="礼品机区域" align="center">
          <el-table-column label="金额" align="center">
            <template slot-scope="scope">
              <el-button @click="getRegion(scope.row)" type="text" size="mini" :class="top_list[1].a1>top_list[0].a1*1.1?'ok':''">{{scope.row.a1}}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.a2}}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="礼品柜区域" align="center">
          <el-table-column label="金额" align="center">
            <template slot-scope="scope">
              <el-button @click="getRegion(scope.row)" type="text" size="mini" :class="top_list[1].a3>top_list[0].a3*1.1?'ok':''">{{scope.row.a3}}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.a4}}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="摊位机区域" align="center">
          <el-table-column label="金额" align="center">
            <template slot-scope="scope">
              <el-button @click="getRegion(scope.row)" type="text" size="mini" :class="top_list[1].a5>top_list[0].a5*1.1?'ok':''">{{scope.row.a5}}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.a6}}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="企划区域" align="center">
          <el-table-column label="金额" align="center">
            <template slot-scope="scope">
              <el-button @click="getRegion(scope.row)" type="text" size="mini" :class="top_list[1].a7>top_list[0].a7*1.1?'ok':''">{{scope.row.a7}}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.a8}}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="其他区域" align="center">
          <el-table-column label="金额" align="center">
            <template slot-scope="scope">
              <el-button @click="getRegion(scope.row)" type="text" size="mini" :class="top_list[1].a9>top_list[0].a9*1.1?'ok':''">{{scope.row.a9}}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.a10}}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="合计" align="center">
          <el-table-column label="金额" align="center">
            <template slot-scope="scope">
              <span :class="top_list[1].a11>top_list[0].a11*1.1?'ok':''">{{scope.row.a11}}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.a12}}</span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
    <!-- 自定义底部 -->
    <div class="bottom_box" style="margin:0 14px">
      <el-button type="text" size="small" @click="dialogClean">清空购物车</el-button>
      <el-button type="text" size="small" @click="selectRegion()">批量选择区域</el-button>
      <el-button class="pull-right" size="small" type="primary" @click="receiving()">提交订单</el-button>
      <p class="pull-right" style="line-height:0">
        种类合计：{{allCarList.length}}种 数量合计：{{totalOrder}}个 金额合计(不含运费)：{{totalPrice|keepTwoNum}}元
      </p>
    </div>
    <!-- 提交订单弹出窗口 -->
    <el-dialog :visible.sync="receiving_information" width="1100px" title="收货信息" @close="onCommitDialogClose">
      <!-- 收货信息 -->
      <el-row>
        <el-col :span=7>
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">采购渠道：</span>
            <span style="width:70%;font-size:14px">{{this.saveForm.type==1?"供应商":"中央仓"}}</span>
          </div>
        </el-col>
        <el-col :span=7>
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">{{usedfor!=2?'门店：':'收货仓：'}}</span>
            <el-select v-if="usedfor!=2" style="width:70%;" placeholder="请选择门店" v-model="saveForm.store_id" filterable clearable disabled>
              <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-else style="width:70%;" v-model="saveForm.house_id" filterable>
              <el-option v-for="item in houseList" :key="item.house_id" :label="item.house_name" :value="item.house_id"></el-option>
            </el-select>
          </div>
        </el-col>
        <el-col :span=10>
          <div class="row-block">
            <span v-if="usedfor!=2" style="width:30%;text-align:right;font-size:14px">收货仓：</span>
            <span v-if="usedfor!=2" style="width:70%;font-size:14px">{{this.house_name_in}}</span>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span=7>
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">收货人：</span>
            <el-input :disabled="true" style="width:70%;font-size:14px" placeholder="请输入姓名" v-model="saveForm.name"></el-input>
          </div>
        </el-col>
        <el-col :span=7>
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">电话：</span>
            <el-input :disabled="true" style="width:70%;" placeholder="请输入手机号码" v-model="saveForm.phone"></el-input>
          </div>
        </el-col>
        <el-col :span=10>
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">地区：</span>
            <div style="width:70%;">
              <keep-alive>
                <dj-region style="width:100%;font-size:14px" :disabled="true" :updateData="updateRegion" :getName="true" :isClear="clearRegion"
                  @provVal="provVal(arguments)" @cityVal="cityVal(arguments)" @areaVal="areaVal(arguments)" ref="region"></dj-region>
              </keep-alive>
            </div>
          </div>
        </el-col>
      </el-row>
      <div class="row-block-full">
        <span style="width:8.75%;text-align:right;font-size:14px">详细地址：</span>
        <el-input :disabled="true" style="width:91.25%;font-size:14px" type="textarea" :rows="2" :maxlength="160" placeholder="请输入详细地址" resize="none"
          v-model="saveForm.address">
        </el-input>
      </div>
      <div class="row-block-full">
        <div style="width:8.75%;text-align:right;font-size:14px">订单信息：</div>
        <p style="width:91.25%;text-align:center;font-size:16px">
          种类合计：{{allCarList.length}}种 数量合计：{{totalOrder}}个 金额合计(不含运费)：{{totalPrice|keepTwoNum}}元
        </p>
      </div>
      <div class="row-block-full">
        <span style="width:8.75%;text-align:right;font-size:14px">订单备注：</span>
        <div style="width:91.25%;height:200px;font-size:14px">
          <el-input style="display:inline-block;width:100%;height:50%" type="textarea" :rows="4" placeholder="备注" resize="none" :disabled="true"
            v-model="remarkInfo"></el-input>
          <el-input style="display:inline-block;width:100%;height:50%" type="textarea" :rows="4" placeholder="备注" v-model="saveForm.remark" resize="none"
            :maxlength="160"></el-input>
        </div>
      </div>
      <div style="width:100%;position:absolute;right: 30px;bottom: 35px;text-align: right;">
        <el-button @click="receiving_information = false">返回修改</el-button>
        <el-button type="primary" @click="saveClick()">确定提交</el-button>
      </div>
    </el-dialog>
    <!-- 批量选择区域弹出窗口 -->
    <el-dialog width="400px" style="height:500px;overflow:hidden" :close-on-click-modal="false" title="批量选择区域" :visible.sync="addDialog">
      <div>
        <div class="area_item">
          <span class="item_left">种类：</span>
          <p class="item_right">{{kind}}（种）</p>
        </div>
        <div class="area_item">
          <span class="item_left">数量：</span>
          <p class="item_right">{{number}}（个）</p>
        </div>
        <div class="area_item">
          <span class="item_left">金额：</span>
          <p class="item_right">{{money|keepTwoNum}}（元）</p>
        </div>
        <div class="area_item">
          <span class="item_left">活动区域</span>
          <p class="item_right">
            <el-select v-model="region">
              <el-option v-for="item in gift_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="changeAllArea()">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 选择区域 -->
    <region-use-dialog ref="regionUseDialog" :area_type="area_type" @change_area_type="change_area_type"></region-use-dialog>
  </div>
</template>
<script>
// 修改购物车
import { editCart } from '@/api/common/gift_purchase.js';
// 获取有权限的门店，获取所有门店，获取门店主仓的收货地址
import { getStoreList, getStoreHouseAdress, updateGiftArea } from '@/api/common/store.js';
import { house, getHouse, car, delGift, delCarList, save } from '@/api/goodsflow/gift_platform.js';
import { integer1to999999 } from '@/utils/validate';
import { getAllInfo, getOrderIndex } from '@/api/dashboard/orderIndex';
import { DjGiftSearchSelect } from '@/components/gift';
import regionUseDialog from '@/components/order/regionUseDialog';
import { DjStoreSelect } from '@/components/store';
export default {
  components: {
    'dj-gift-search-select': DjGiftSearchSelect,
    'region-use-dialog': regionUseDialog,
    'dj-store-select': DjStoreSelect
  },
  data() {
    return {
      gift_list: [
        { name: '礼品机区域', id: '1' },
        { name: '礼品柜区域', id: '2' },
        { name: '摊位机区域', id: '3' },
        { name: '企划区域', id: '4' },
        { name: '其他区域', id: '5' }
      ],
      area_list: [
        { id: '1', name: '礼品机区域' },
        { id: '2', name: '礼品柜区域' },
        { id: '3', name: '摊位机区域' },
        { id: '4', name: '企划区域' },
        { id: '5', name: '其他区域' },
        { id: '6', name: '未配置' },
        { id: '7', name: '已配置' },
        { id: '8', name: '全部' }
      ],
      top_list: [
        { name: '订货预估', a1: 0, a2: 0, a3: 0, a4: 0, a5: 0, a6: 0, a7: 0, a8: 0, a9: 0, a10: 0, a11: 0, a12: 0 },
        { name: '订货累计', a1: 0, a2: 0, a3: 0, a4: 0, a5: 0, a6: 0, a7: 0, a8: 0, a9: 0, a10: 0, a11: 0, a12: 0 }
      ],
      global: {
        store_name: '',
        starttime: '',
        store_id: ''
      },
      region: '1',
      giftId_list: '',
      type_list: '',
      area_type: {},
      kind: 0,
      number: 0,
      money: 0,
      formInline: {
        store_id: this.$store.getters.optionId,
        look_del: ''
      },
      usedfor: '', // 1:运管系统门店采购下单，2：采购平台总部给中央仓下单，3：采购平台总部统配给门店
      updateRegion: {}, // 更新子组件region时传值
      clearRegion: false, // 清空子组件region中的值
      carList: [], // 用于显示的购物车礼品
      allCarList: [], // 实际真实的购物车礼品
      route: { name: 'warehouse/shoppingcar' },
      receiving_information: false,
      gift_other_information: false,
      listLoading: false,
      addDialog: false,
      storeList: [],
      houseList: [],
      remarkInfo: '',
      exportForm: [],
      house_name_in: '', //收货仓名称 需手动选择
      saveForm: {
        type: '', //1：供应商，2：中央仓
        name: '', //收货人
        phone: '', //电话
        prov: '', //省份
        city: '', //城市
        dist: '', //区域
        house_id: '', //收获仓
        store_id: '', //门店
        order_list: [], //购买了哪些商品
        remark: '', //备注
        address: ''
      },
      searchObj: {
        name: '',
        gift_id: '',
        no_obsolete: '',
        gb_code: '',
        area_type: '8'
      }
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (vm.$route.params.routerflag) {
        vm.usedfor = vm.$route.params.usedfor;
        vm.saveForm.type = vm.$route.params.from;
        vm.resetSaveForm();
        //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
        if (vm.usedfor != 2) {
          vm.getStore();
        } else {
          vm.getUidHouse();
        }
        vm.getCar();
        vm.startTime();
      }
    });
  },
  methods: {
    // 清空购物车弹出框
    dialogClean() {
      this.$confirm('确定清空购物车?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delCarListClick();
        })
        .catch(() => {});
    },
    startTime() {
      let date = new Date().getDate() < 9 ? new Date().getMonth() + 1 : new Date().getMonth() + 2;
      this.global.starttime = `${new Date().getFullYear()}-${date}`;
    },
    selectStoreChanged(obj, item) {
      for (let key in obj) this.formInline[key] = obj[key];
      this.global.store_name = item.name;
      this.global.store_id = item.id;
      this.getAllInfo();
      this.saveForm.store_id = item.id;
    },
    // 指标
    getAllInfo() {
      getAllInfo({ store_id: this.formInline.store_id, start_time: this.global.starttime })
        .then(res => {
          if (res.code == 1) {
            res.data.forEach(val => {
              val.cumulative_money = val.cumulative_money / 1000000;
              val.booking_money = val.booking_money / 1000000;
              val.cumulative_num = val.cumulative_num / 1;
              val.booking_num = Math.ceil(val.booking_num / 1);
              this.carList &&
                this.carList.forEach(item => {
                  let area_type = item.area_type > 100 ? item.area_type / 100 : item.area_type;
                  if (area_type == val.area_type) {
                    val.cumulative_money += item.num * item.money_sell;
                    val.cumulative_num += item.num / 1;
                  }
                });
              switch (val.area_type / 1) {
                case 1:
                  this.getTopData(val, 'a1', 'a2');
                  break;
                case 2:
                  this.getTopData(val, 'a3', 'a4');
                  break;
                case 3:
                  this.getTopData(val, 'a5', 'a6');
                  break;
                case 4:
                  this.getTopData(val, 'a7', 'a8');
                  break;
                case 5:
                  this.getTopData(val, 'a9', 'a10');
                  break;
                default:
                  break;
              }
            });
          }
          this.top_list &&
            this.top_list.forEach(val => {
              val.a11 = (val.a1 / 1 + val.a3 / 1 + val.a5 / 1 + val.a7 / 1 + val.a9 / 1).toFixed(2);
              val.a12 = val.a2 / 1 + val.a4 / 1 + val.a6 / 1 + val.a8 / 1 + val.a10 / 1;
            });
        })
        .catch(err => {
          return;
        });
    },
    getRegion(row) {
      this.$router.push({
        name: 'operation/category_order_indicator',
        params: {
          row: row,
          global: this.global,
          routerflag: true
        }
      });
    },
    // 更改区域
    change_area_type(area_type, row) {
      updateGiftArea({ type: row.type, gift_list: row.gift_id, area_type: area_type }).then(res => {
        if (res.code == 1) {
          row.area_type = area_type;
        }
      });
    },
    regionUse(row) {
      this.area_type = row;
      this.$refs.regionUseDialog.show();
    },
    // 批量更改区域
    selectRegion() {
      this.number = 0;
      this.money = 0;
      this.giftId_list = '';
      this.type_list = null;
      this.kind = this.exportForm.length;
      this.exportForm &&
        this.exportForm.forEach(item => {
          this.giftId_list += item.gift_id + ',';
          this.type_list = item.type;
          this.number += item.num / 1;
          this.money += (item.num / 1) * (item.money_sell / 1);
        });
      this.addDialog = true;
    },
    // 保存
    changeAllArea() {
      if (this.exportForm.length == 0) {
        this.$message.error('未选择礼品');
        return;
      }
      updateGiftArea({ type: this.type_list, gift_list: this.giftId_list, area_type: this.region }).then(res => {
        this.getCar();
        this.exportForm = [];
        this.addDialog = false;
      });
    },
    handleSelectionChange(val) {
      this.exportForm = val;
    },
    onEditSaveCancel(type, scope) {
      if (type == 1) {
        // 点击了编辑按钮
        scope.row.isEdit = true;
        scope.row.pre_eidt_num = scope.row.num;
      } else if (type == 2) {
        if (scope.row.area_type == 0) {
          this.$message.error('请选择使用区域');
          return;
        }
        let val = {
          gift_id: scope.row.gift_id,
          now_num: scope.row.num, // 添加购物车用shop_num，修改购物车用now_num
          type: this.saveForm.type,
          money: scope.row.money_sell,
          area_type: scope.row.area_type > 100 ? scope.row.area_type / 100 : scope.row.area_type
        };
        editCart(val, this.usedfor).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            scope.row.isEdit = false;
          }
        });
        this.getAllInfo();
      } else {
        // 点击了取消按钮
        scope.row.isEdit = false;
        scope.row.num = scope.row.pre_eidt_num;
      }
    },
    // 搜索输入框内容发生变化
    searchTextChanged(obj) {
      for (let key in obj) this.searchObj[key] = obj[key];
    },
    numberChange(index) {
      if (this.carList[index].num > 999999) {
        this.carList[index].num = this.carList[index].num.slice(0, 6);
      }
      if (this.carList[index].num * 1 > this.carList[index].house_num * 1) {
        this.carList[index].num = this.carList[index].house_num;
      }
    },
    resetSaveForm() {
      this.house_name_in = '';
      this.saveForm.house_id = '';
      this.saveForm.prov = '';
      this.saveForm.prov_name = '';
      this.saveForm.city = '';
      this.saveForm.city_name = '';
      this.saveForm.dist = '';
      this.saveForm.dist_name = '';
      this.saveForm.address = '';
      this.saveForm.name = '';
      this.saveForm.phone = '';
      this.saveForm.remark = '';
      this.clearRegion = true; //重置订单确认弹窗中的地区
    },
    onCommitDialogClose() {
      this.clearRegion = false; //取消重置订单确认弹窗中的地区
    },
    // 购物车点提交，校验购物车数据
    receiving() {
      if (this.allCarList.length == 0) {
        this.$message.error('购物车没有商品');
        return;
      }
      for (var i = 0; i < this.allCarList.length; i++) {
        if (this.allCarList[i].isEdit) {
          this.$message.error('修改未保存，请先保存再提交');
          return;
        }
        if (this.allCarList[i].is_on_sale == 0) {
          this.$message.error('购物车中存在已下架商品，请先移除再提交');
          return;
        }
        if (!integer1to999999(this.allCarList[i].num)) {
          this.$message.error('请将数量填写完整,并且数量只能为1-999999的整数!');
          return;
        }
        if (this.saveForm.type == 2 && this.allCarList[i].num * 1 > this.allCarList[i].house_num * 1) {
          this.$message.error('数量不能大于剩余库存!');
          return;
        }
        if (this.allCarList[i].area_type == 0) {
          this.$message({
            message: '部分礼品未选择礼品区域，请先选择礼品区域',
            type: 'error',
            duration: 5000
          });
          return;
        }
      }
      if (this.saveForm.store_id) {
        this.saveForm.prov = '';
        this.saveForm.city = '';
        this.saveForm.dist = '';
        this.saveForm.prov_name = '';
        this.saveForm.city_name = '';
        this.saveForm.dist_name = '';
        this.saveForm.address = '';
        this.saveForm.name = '';
        this.saveForm.phone = '';
        this.saveForm.house_id = '';
        this.house_name_in = '';
        this.getHouseAdress();
      } else {
        this.updateRegion = {
          prov: '',
          city: '',
          area: ''
        };
        this.saveForm.prov = '';
        this.saveForm.city = '';
        this.saveForm.dist = '';
        this.saveForm.prov_name = '';
        this.saveForm.city_name = '';
        this.saveForm.dist_name = '';
        this.saveForm.address = '';
        this.saveForm.name = '';
        this.saveForm.phone = '';
        this.saveForm.house_id = '';
        this.house_name_in = '';
      }
      let remark = '';
      for (var elem of this.allCarList) {
        if (elem.remark && elem.remark.trim().length > 0) {
          remark += '【' + elem.gift_id + '#' + elem.name + '】' + elem.remark.trim() + ';';
        }
      }
      this.remarkInfo = remark;
      this.receiving_information = true;
    },
    // 完善收货信息后，确认下单
    saveClick() {
      if (!this.saveForm.name || !this.saveForm.name.trim()) {
        this.$message.error('收货人未填写');
        return;
      }
      if (!this.saveForm.phone || !this.saveForm.phone.trim()) {
        this.$message.error('手机号未填写');
        return;
      }
      if (!this.saveForm.prov_name || !this.saveForm.city_name) {
        this.$message.error('请选择地区');
        return;
      }
      if (!this.saveForm.address || !this.saveForm.address.trim()) {
        this.$message.error('请填写详细地址');
        return;
      }
      let nameReg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/; //验证姓名正则
      if (!nameReg.test(this.saveForm.name.trim())) {
        this.$message.error('收货人名称不规范');
        return;
      }
      let phoneReg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (!phoneReg.test(this.saveForm.phone)) {
        this.$message.error('电话号码格式不正确');
        return;
      }
      this.saveForm.name = this.saveForm.name.trim();
      this.saveForm.address = this.saveForm.address.trim();
      this.saveForm.order_list = [];
      this.allCarList.forEach(val => {
        let obj = {
          total_num: val.num,
          gift_id: val.gift_id,
          type: this.saveForm.type,
          look_money: val.money_sell,
          remark: val.remark,
          area_type: val.area_type
        };
        this.saveForm.order_list.push(obj);
      });
      save(this.saveForm).then(res => {
        if (res.code == 1) {
          this.$message.success(res.message);
          this.receiving_information = false;
          this.$store.dispatch('delVisitedViews', this.route).then(() => {
            this.$router.push({
              name: 'warehouse/gift_purchase',
              params: { routerflag: 1 }
            });
          });
        }
      });
    },
    getCar() {
      this.listLoading = true;
      this.carList = [];
      car({ type: this.saveForm.type })
        .then(response => {
          if (response && response.length > 0) {
            response.forEach(val => {
              val.remark = '';
              val.isEdit = false;
              val.pre_eidt_num = val.gift_num;
            });
            this.allCarList = response;
            this.carList = [];
            this.carList.push(...this.allCarList);
          } else {
            this.allCarList = [];
            this.carList = [];
          }
          this.listLoading = false;
          // this.getAllInfo();
          setTimeout(() => {
            this.getAllInfo();
          }, 1000);
        })
        .catch(res => {
          this.listLoading = false;
        });
    },
    getStore() {
      getStoreList({ category_id: 448 }).then(response => {
        this.storeList = response;
      });
    },
    getTopData(data, type, num) {
      this.top_list[0][type] = (data.booking_money / 1).toFixed(2);
      this.top_list[1][type] = (data.cumulative_money / 1).toFixed(2);
      this.top_list[0][num] = data.booking_num / 1;
      this.top_list[1][num] = data.cumulative_num / 1;
    },
    // 获取主仓收货地址
    getHouseAdress() {
      this.saveForm.house_id = '';
      getStoreHouseAdress({ store_id: this.saveForm.store_id }).then(response => {
        if (response) {
          this.updateRegion = {
            prov: response.prov_id,
            city: response.city_id,
            area: response.dist_id
          };
          this.saveForm.prov = response.prov_id;
          this.saveForm.city = response.city_id;
          this.saveForm.dist = response.dist_id;
          this.saveForm.prov_name = response.prov_name ? response.prov_name : '';
          this.saveForm.city_name = response.city_name ? response.city_name : '';
          this.saveForm.dist_name = response.dist_name ? response.dist_name : '';
          this.saveForm.address = response.address;
          this.saveForm.name = response.linkman;
          this.saveForm.phone = response.phone;
          this.saveForm.house_id = response.house_id;
          this.house_name_in = response.house_name;
        }
      });
    },
    getUidHouse() {
      getHouse({}).then(response => {
        this.houseList = response;
        this.saveForm.house_id = response.length > 0 ? response[0].house_id : '';
      });
    },
    // 子组件传过来的省
    provVal(val) {
      this.saveForm.prov = val[0];
      this.saveForm.prov_name = val[1];
    },
    // 子组件传过来的市
    cityVal(val) {
      this.saveForm.city = val[0];
      this.saveForm.city_name = val[1];
    },
    // 子组件传过来的区
    areaVal(val) {
      this.saveForm.dist = val[0];
      this.saveForm.dist_name = val[1];
    },
    // 清空购物车
    delCarListClick() {
      delCarList({ type: this.saveForm.type }).then(response => {
        this.$message({
          type: response.code == 1 ? 'success' : 'error',
          message: response.message
        });
        if (response.code == 1) {
          this.carList = [];
          this.allCarList = [];
          this.getAllInfo();
        }
      });
    },
    // 删除购物车礼品
    delClick(scope) {
      this.$confirm('确定移除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delGift({ gift_id: scope.row.gift_id, type: this.saveForm.type }).then(response => {
          this.$message({
            type: response.code == 1 ? 'success' : 'error',
            message: response.message
          });
          if (response.code == 1) {
            this.carList.splice(scope.$index, 1);
            this.removeArray(this.allCarList, scope.row);
            this.getAllInfo();
          }
        });
      });
    },
    // 删除数组中的某一个对象_arr:数组 _obj:需删除的对象
    removeArray(_arr, _obj) {
      var length = _arr.length;
      for (var i = 0; i < length; i++) {
        if (_arr[i] == _obj) {
          if (i == 0) {
            _arr.shift(); //删除并返回数组的第一个元素
            return _arr;
          } else if (i == length - 1) {
            _arr.pop(); //删除并返回数组的最后一个元素
            return _arr;
          } else {
            _arr.splice(i, 1); //删除下标为i的元素
            return _arr;
          }
        }
      }
    },
    // 筛选按钮
    searchClick() {
      this.carList = [...this.allCarList];
      for (let key in this.searchObj) {
        if (this.searchObj[key]) {
          this.searchBy(key);
        }
      }
    },
    searchBy(key) {
      let searchVal = this.searchObj[key];
      if (key == 'name') {
        this.carList = this.carList.filter(val => val[key].indexOf(searchVal) >= 0);
      } else if (key == 'area_type') {
        this.carList = this.carList.filter(val => {
          switch (searchVal) {
            case '6':
              return val[key] == 0;
            case '7':
              return val[key] >= 1;
            case '8':
              return val[key] || val[key] == 0;
            default:
              return val[key] / 100 == searchVal || val[key] == searchVal;
          }
        });
      } else {
        this.carList = this.carList.filter(val => val[key] == searchVal);
      }
    }
  },
  computed: {
    totalOrder: function() {
      let num = 0;
      this.allCarList.forEach(val => {
        num = val.num * 1 + num;
      });
      return num;
    },
    totalPrice: function() {
      let total = 0;
      this.allCarList.forEach(val => {
        total = val.num * val.money_sell + total;
      });
      return total;
    }
  }
};
</script>
<style scoped>
.app-container >>> .customContainer {
  min-width: 1350px;
}
.app-container >>> .el-table--scrollable-x .el-table__body-wrapper {
  overflow-x: hidden;
}
.app-container >>> .el-dialog {
  height: 650px;
}

.app-container >>> .el-dialog input {
  height: 32px !important;
}

.app-container >>> .el-dialog textarea {
  border-radius: unset;
  padding: 10px 15px;
}

.app-container >>> .el-dialog select {
  width: 32.3%;
}

.app-container >>> .el-dialog .el-dialog__body {
  padding: 30px;
}

.row-block {
  width: 100%;
  height: 50%;
  margin: 8px 0;
  display: flex;
  align-items: center;
}

.row-block-full {
  width: 100%;
  height: 100%;
  margin-top: 8px;
  display: flex;
  align-items: center;
}
.area_item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item_left {
  margin: 10px 0;
  display: inline-block;
  width: 20%;
  text-align: right;
}
.item_right {
  margin: 0;
  width: 70%;
}
.ok {
  color: red;
}
</style>